package LUNCH;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class CreateXML {
	
	static Map<String, List<String[]>> map =null;
	
	
	public CreateXML(Map<String, List<String[]>> map) {
		this.map = map;
		XMLUTIL() ;
	}

	public static void CreateElement(Document doc) {
		Element root = doc.createElement("午餐统计");

		Iterator<?> it1 = null;
		Map.Entry entry = null;
		it1 = map.entrySet().iterator();
		while (it1.hasNext()) {
			entry = (Map.Entry) it1.next();
			List<String[]> list = (List<String[]>) entry.getValue();
			int len = list.size();
			for (int i = 0; i < len; i++) {
				String LunchInfo[] = list.get(i);

				Element name = doc.createElement("姓名");
				name.setAttribute("name", LunchInfo[0]);

				Element monery = doc.createElement("金额");
				Element date = doc.createElement("日期");
				Element remark = doc.createElement("备注");

				Text moneryText = doc.createTextNode(LunchInfo[1]);
				Text dateText = doc.createTextNode(LunchInfo[2]);
				Text remarkText = doc.createTextNode(LunchInfo[3]);

				monery.appendChild(moneryText);
				date.appendChild(dateText);
				remark.appendChild(remarkText);

				name.appendChild(monery);
				name.appendChild(date);
				name.appendChild(remark);
				root.appendChild(name);
			}
		}
		doc.appendChild(root);
	}

	public static void XMLUTIL() {
		// 实例化解析器
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			// 创建Document对象
			Document doc = builder.newDocument();
			// 创建XML文件所需的各种对象并序列化
			CreateElement(doc);
			doc2XmlFile(doc, "C:\\lunch.xml");
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static boolean doc2XmlFile(Document document, String filename) {
		boolean flag = true;
		try {
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer();
			/** 编码 */
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(new File(filename));
			transformer.transform(source, result);
		} catch (Exception ex) {
			flag = false;
			ex.printStackTrace();
		}
		return flag;
	}
}
